const db = require('../db/index')

//获取文章函数处理模块
exports.getCate = (req, res) => {
    const sql = `select * from ev_article_cate where is_delete=0`

    db.query(sql, [], (err, results) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '获取文章列表成功',

            data: results
        })
    })
}

//添加文章函数处理模块
exports.addCate = (req, res) => {
    const sql = `select * from ev_article_cate where name=? or alias=?`
    const { name, alias } = req.body
    db.query(sql, [name, alias], (err, results) => {
        if (err) return res.cc(err)
        if (results.length > 0) return res.cc('分类名称或别名重复！')
        const sql = `insert into ev_article_cate set ?`
        db.query(sql, { name, alias }, (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows != 1) return res.cc('添加失败')
            res.send({
                status: 0,
                message: '新增文章分类成功！',
            })
        })
    })
}

//通过Id删除文章函数处理模块
exports.deleteCateById = (req, res) => {
    const sql = `update ev_article_cate set is_delete=1 where Id=?`
    const { id } = req.params
    db.query(sql, [id], (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows != 1) return res.cc('删除失败')
        res.send({
            status: 0,
            message: '删除文章分类成功！',
        })
    })

}

//通过Id获取文章函数处理模块
exports.getCateById = (req, res) => {
    const sql = `select * from ev_article_cate where Id=?`
    const { id } = req.params
    db.query(sql, [id], (err, results) => {
        if (err) return res.cc(err)
        if (results.length !== 1) return res.cc('获取文章失败')
        res.send({
            status: 0,
            message: '获取文章分类数据成功！',
            data: results[0]
        })
    })
}

//通过Id更新文章函数处理模块
exports.updateCateById = (req, res) => {
    const sql = `select * from ev_article_cate where (name=? or alias=?) and (Id !=? and is_delete=1)`

    // const sql = `update ev_article_cate set name=?,alias=? where Id=?`
    console.log(req.body);
    const { name, alias, Id } = req.body
    db.query(sql, [name, alias, Id], (err, results) => {
        if (err) return res.cc(err)
        if (results.length > 0) return res.cc('分类名称或者别名重复')
        const sql = `update ev_article_cate set name=?,alias=? where Id=?`
        db.query(sql, [name, alias, Id], (err, results) => {
            if (err) return res.cc(err)
            if (results.affectedRows !== 1) return res.cc('获取文章失败')
            res.send({
                status: 0,
                message: '更新文章分类数据成功！'
            })
        })

    })

}